<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\admin\model\Admin as AdminModel;
use app\admin\model\scanwork\Order;
use app\admin\model\scanwork\Allocation;
use app\admin\model\scanwork\Report;
use app\admin\model\scanwork\Product;
use app\admin\model\scanwork\ProductModel;
use app\admin\model\scanwork\Process;
use think\Db;
use think\Exception;

/**
 * 钉钉小程序API控制器
 * 整合员工端和管理端功能
 */
class Dingding extends Api
{
    protected $noNeedLogin = [
        'dingdingLogin', 'checkDingdingToken', 'test', 'dbTest', 'uploadImage', 'autoLogin',
        'getUserInfo', 'updateUserInfo', 'profile', 'getUnreadMessageCount', 'getLatestMessages',
        'getReports', 'getActiveReports', 'getTasks', 'getReportData', 'submitReport', 'getRecords', 
        'getWageStats', 'getStats', 'getTimeTasks', 'submitTimeReport', 'getTimeRecords', 'getTimeWage', 
        'activeReport', 'getOrders', 'getModels', 'getProcesses', 'getOrderModels', 'getProcessPrice', 
        'getOrderInfo', 'getActiveReportDetail', 'getMessages', 'markMessageRead', 'deleteMessage', 
        'updateSubscribeStatus', 'scanReport', 'getMyAllocations', 'getAllocationDetail',
        'adminLogin', 'checkToken', 'getAllocations', 'auditReport', 'getReportDetail', 'getProducts', 
        'getUsers', 'createAllocation', 'batchCreateAllocation', 'getOrderDetail', 'createOrder', 
        'updateOrder', 'deleteOrder', 'debugOrder', 'uploadAuditImage', 'uploadReportImage', 
        'auditActiveReport'
    ];
    protected $noNeedRight = ['*'];
    
    // 当前用户信息
    protected $currentUser = null;
    protected $currentUserId = null;

    public function _initialize()
    {
        // 重写父类的_initialize方法，跳过通用认证
        $controllername = $this->request->controller();
        $actionname = $this->request->action();
        
        // 初始化auth对象
        $this->auth = \app\common\library\Auth::instance();
        
        // 设置当前请求的URI
        $this->auth->setRequestUri(str_replace('.', '/', $controllername) . '/' . $actionname);
        
        // 检查是否为管理员登录的方法
        $action = $this->request->action();
        $adminMethods = ['getallocations', 'getreports', 'auditreport', 'getreportdetail', 'getusers', 'createallocation', 'batchcreateallocation', 'uploadauditimage', 'getactivereports', 'getactivereportdetail', 'auditactivereport', 'getallocationdetail', 'getorderdetail', 'createorder', 'updateorder', 'deleteorder', 'debugorder'];
        
        file_put_contents('/tmp/dingding_init.log', "初始化调试 - 当前方法: {$action}\n", FILE_APPEND);
        
        if (in_array($action, $adminMethods)) {
            // 验证管理员登录 - 修复认证逻辑
            $this->checkAdminAuth();
        }
        
        // 钉钉token认证 - 对于需要登录的方法（排除管理员方法）
        $needLoginMethods = ['getstats', 'gettasks', 'submitreport', 'getrecords', 'getwagestats', 'gettimetasks', 'submittimereport', 'gettimetecords', 'gettimewage', 'activereport', 'getmyallocations', 'getallocationdetail', 'getactivereportdetail', 'profile', 'getuserinfo', 'getmessages', 'getprocesses', 'gettimetasks', 'getproducts', 'getmodels', 'getorders', 'getordermodels'];
        
        // 不需要登录的方法（登录相关）
        $noAuthMethods = ['dingdinglogin', 'bindexistinguser', 'createnewuser', 'dingdingLogin', 'bindExistingUser', 'createNewUser', 'searchusers', 'searchUsers', 'adminlogin', 'adminLogin'];
        
        file_put_contents('/tmp/dingding_init.log', "初始化调试 - 需要登录的方法: " . implode(',', $needLoginMethods) . "\n", FILE_APPEND);
        file_put_contents('/tmp/dingding_init.log', "初始化调试 - 当前方法是否在列表中: " . (in_array($action, $needLoginMethods) ? '是' : '否') . "\n", FILE_APPEND);
        
        if (in_array($action, $needLoginMethods)) {
            file_put_contents('/tmp/dingding_init.log', "初始化调试 - 开始调用checkDingdingAuth\n", FILE_APPEND);
            $this->checkDingdingAuth();
        } elseif (in_array($action, $noAuthMethods)) {
            file_put_contents('/tmp/dingding_init.log', "初始化调试 - 登录相关方法，跳过认证\n", FILE_APPEND);
        } else {
            file_put_contents('/tmp/dingding_init.log', "初始化调试 - 其他方法，跳过认证\n", FILE_APPEND);
        }
        
        // 加载当前控制器语言包
        $this->loadlang($controllername);
    }
    
    /**
     * 检查管理员认证
     */
    private function checkAdminAuth()
    {
        // 参考微信小程序，使用session认证
        $adminToken = session('admin_token');
        $adminInfo = session('admin_info');
        
        // 记录调试信息
        file_put_contents('/tmp/dingding_admin_auth.log', "管理员认证调试 - Session Token: " . ($adminToken ?: 'null') . "\n", FILE_APPEND);
        file_put_contents('/tmp/dingding_admin_auth.log', "管理员认证调试 - Session Info: " . ($adminInfo ? 'exists' : 'null') . "\n", FILE_APPEND);
        
        if (!$adminToken || !$adminInfo) {
            file_put_contents('/tmp/dingding_admin_auth.log', "管理员认证失败 - Session中无管理员信息\n", FILE_APPEND);
            $this->error('请先登录', null, 401);
        }
        
        // 验证管理员用户是否存在
        $user = User::find($adminInfo['id']);
        if (!$user) {
            file_put_contents('/tmp/dingding_admin_auth.log', "管理员认证失败 - 用户不存在\n", FILE_APPEND);
            $this->error('用户不存在', null, 401);
        }
        
        file_put_contents('/tmp/dingding_admin_auth.log', "管理员认证成功 - 用户ID: {$user->id}, 用户名: {$user->username}\n", FILE_APPEND);
        
        // 使用Auth类的direct方法设置用户
        $this->auth->direct($user->id);
        
        // 同时设置到当前控制器属性
        $this->currentUser = $user;
        $this->currentUserId = $user->id;
        
        // 保存到session
        session('dingding_current_user_id', $user->id);
        session('dingding_current_user', $user);
        
        file_put_contents('/tmp/dingding_admin_auth.log', "管理员认证完成 - currentUserId: {$this->currentUserId}\n", FILE_APPEND);
    }

    /**
     * 检查钉钉认证
     */
    private function checkDingdingAuth()
    {
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }
        
        // 处理Bearer token格式
        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }
        
        // 记录调试信息
        file_put_contents('/tmp/dingding_auth.log', "钉钉认证调试 - Token: {$token}\n", FILE_APPEND);
        
        // 从数据库验证token
        $user = User::where('dingding_token', $token)
                   ->where('dingding_token_expire', '>', time())
                   ->find();
        
        if (!$user) {
            file_put_contents('/tmp/dingding_auth.log', "钉钉认证失败 - 用户未找到或token过期\n", FILE_APPEND);
            $this->error('token无效或已过期', null, 401);
        }
        
        file_put_contents('/tmp/dingding_auth.log', "钉钉认证成功 - 用户ID: {$user->id}, 用户名: {$user->username}\n", FILE_APPEND);
        
        // 使用Auth类的direct方法设置用户
        $this->auth->direct($user->id);
        
        // 同时设置到当前控制器属性
        $this->currentUser = $user;
        $this->currentUserId = $user->id;
        
        // 保存到session
        session('dingding_current_user_id', $user->id);
        session('dingding_current_user', $user);
        
        file_put_contents('/tmp/dingding_auth.log', "钉钉认证完成 - currentUserId: {$this->currentUserId}\n", FILE_APPEND);
        file_put_contents('/tmp/dingding_auth.log', "钉钉认证完成 - currentUser: " . ($this->currentUser ? 'exists' : 'null') . "\n", FILE_APPEND);
        file_put_contents('/tmp/dingding_auth.log', "钉钉认证完成 - 用户ID类型: " . gettype($this->currentUserId) . "\n", FILE_APPEND);
        file_put_contents('/tmp/dingding_auth.log', "钉钉认证完成 - session用户ID: " . session('dingding_current_user_id') . "\n", FILE_APPEND);
        file_put_contents('/tmp/dingding_auth.log', "钉钉认证完成 - auth是否登录: " . ($this->auth->isLogin() ? '是' : '否') . "\n", FILE_APPEND);
    }

    /**
     * 钉钉小程序登录
     */
    public function dingdingLogin()
    {
        $code = $this->request->post('code');
        $corpId = $this->request->post('corp_id');
        
        if (!$code || !$corpId) {
            $this->error('参数不完整');
        }
        
        try {
            // 获取真实钉钉用户信息
            $dingdingUserInfo = $this->getDingdingUserInfo($code, $corpId);
            
            if (!$dingdingUserInfo) {
                $this->error('钉钉登录失败');
            }
            
            // 先通过钉钉userid查找是否已绑定
            $existingUser = User::where('dingding_userid', $dingdingUserInfo['userid'])->find();
            
            if ($existingUser) {
                // 已绑定，直接登录
                $user = $existingUser;
                $token = md5($user->id . time() . rand(1000, 9999));
                
                // 保存token到数据库
                $user->dingding_token = $token;
                $user->dingding_token_expire = time() + 7200; // 2小时过期
                $user->save();
                
                // 保存到session
                $sessionData = [
                    'user_id' => $user->id,
                    'dingding_user_id' => $dingdingUserInfo['userid'],
                    'corp_id' => $corpId,
                    'name' => $dingdingUserInfo['name'],
                    'department_ids' => $dingdingUserInfo['department_ids'] ?? [],
                    'login_time' => time()
                ];
                
                session('dingding_user_info', $sessionData);
                session('dingding_token', $token);
                
                $this->success('登录成功', [
                    'token' => $token,
                    'user' => $user,
                    'dingding_info' => $dingdingUserInfo,
                    'need_choice' => false
                ]);
            } else {
                // 首次登录，需要用户选择
                // 查找可能的现有用户（通过手机号或邮箱）
                $possibleUsers = [];
                
                // 只有当手机号不为空时才进行匹配
                if (!empty($dingdingUserInfo['mobile'])) {
                    $mobileUser = User::where('mobile', $dingdingUserInfo['mobile'])->find();
                    if ($mobileUser) {
                        $possibleUsers[] = [
                            'id' => $mobileUser->id,
                            'username' => $mobileUser->username,
                            'nickname' => $mobileUser->nickname,
                            'mobile' => $mobileUser->mobile,
                            'email' => $mobileUser->email,
                            'match_type' => 'mobile'
                        ];
                    }
                }
                
                // 只有当邮箱不为空时才进行匹配
                if (!empty($dingdingUserInfo['email'])) {
                    $emailUser = User::where('email', $dingdingUserInfo['email'])->find();
                    if ($emailUser && $emailUser->id != ($possibleUsers[0]['id'] ?? 0)) {
                        $possibleUsers[] = [
                            'id' => $emailUser->id,
                            'username' => $emailUser->username,
                            'nickname' => $emailUser->nickname,
                            'mobile' => $emailUser->mobile,
                            'email' => $emailUser->email,
                            'match_type' => 'email'
                        ];
                    }
                }
                
                // 生成临时token用于后续操作
                $tempToken = md5('temp_' . $dingdingUserInfo['userid'] . time());
                
                // 保存钉钉用户信息到数据库临时表
                $tempData = [
                    'temp_token' => $tempToken,
                    'dingding_user_info' => json_encode($dingdingUserInfo),
                    'corp_id' => $corpId,
                    'createtime' => time(),
                    'expiretime' => time() + 1800 // 30分钟过期
                ];
                
                // 先删除旧的临时数据
                Db::name('dingding_temp_login')->where('temp_token', $tempToken)->delete();
                
                // 插入新的临时数据
                Db::name('dingding_temp_login')->insert($tempData);
                
                $this->success('需要选择登录方式', [
                    'temp_token' => $tempToken,
                    'dingding_info' => $dingdingUserInfo,
                    'possible_users' => $possibleUsers,
                    'need_choice' => true
                ]);
            }
            
        } catch (Exception $e) {
            $this->error('登录失败：' . $e->getMessage());
        }
    }

    /**
     * 获取钉钉用户信息
     */
    private function getDingdingUserInfo($code, $corpId)
    {
        // 钉钉小程序配置 - 从配置文件读取
        $appId = config('dingding.app_id') ?: '135fdd6c-2ad5-4ab7-ad5f-0f74b38ec088';
        $appSecret = config('dingding.app_secret') ?: 'b-qdpngJmjpbvljvRxFNjcCgo-zLlr3i4NqUCo5rpGZrTv6z4aq5p-3IkyXz_Z79';
        
        // 记录调试信息
        error_log("钉钉登录调试 - AppID: {$appId}, CorpID: {$corpId}, Code: {$code}");
        
        // 获取access_token
        $tokenUrl = "https://oapi.dingtalk.com/gettoken?appkey={$appId}&appsecret={$appSecret}";
        $tokenResult = file_get_contents($tokenUrl);
        $tokenData = json_decode($tokenResult, true);
        
        // 记录token获取结果
        error_log("钉钉token获取结果: " . json_encode($tokenData));
        
        if (!isset($tokenData['access_token'])) {
            $errorMsg = isset($tokenData['errmsg']) ? $tokenData['errmsg'] : '未知错误';
            throw new Exception("获取钉钉access_token失败: {$errorMsg}");
        }
        
        $accessToken = $tokenData['access_token'];
        
        // 获取用户信息
        $userUrl = "https://oapi.dingtalk.com/user/getuserinfo?access_token={$accessToken}&code={$code}";
        $userResult = file_get_contents($userUrl);
        $userData = json_decode($userResult, true);
        
        // 记录用户信息获取结果
        error_log("钉钉用户信息获取结果: " . json_encode($userData));
        
        if (!isset($userData['userid'])) {
            $errorMsg = isset($userData['errmsg']) ? $userData['errmsg'] : '未知错误';
            throw new Exception("获取钉钉用户信息失败: {$errorMsg}");
        }
        
        // 获取用户详细信息
        $detailUrl = "https://oapi.dingtalk.com/user/get?access_token={$accessToken}&userid={$userData['userid']}";
        $detailResult = file_get_contents($detailUrl);
        $detailData = json_decode($detailResult, true);
        
        // 记录用户详细信息获取结果
        error_log("钉钉用户详细信息获取结果: " . json_encode($detailData));
        
        return [
            'userid' => $userData['userid'],
            'name' => $detailData['name'] ?? '钉钉用户',
            'mobile' => $detailData['mobile'] ?? '',
            'email' => $detailData['email'] ?? '',
            'department_ids' => $detailData['department'] ?? [],
            'avatar' => $detailData['avatar'] ?? ''
        ];
    }

    /**
     * 查找或创建钉钉用户
     */
    private function findOrCreateDingdingUser($dingdingUserInfo)
    {
        // 先通过钉钉userid查找
        $user = User::where('dingding_userid', $dingdingUserInfo['userid'])->find();
        
        if (!$user) {
            // 通过手机号查找
            if (!empty($dingdingUserInfo['mobile'])) {
                $user = User::where('mobile', $dingdingUserInfo['mobile'])->find();
            }
            
            // 通过邮箱查找
            if (!$user && !empty($dingdingUserInfo['email'])) {
                $user = User::where('email', $dingdingUserInfo['email'])->find();
            }
            
            if ($user) {
                // 绑定钉钉账号
                $user->dingding_userid = $dingdingUserInfo['userid'];
                $user->dingding_corpid = $dingdingUserInfo['corp_id'] ?? '';
                $user->save();
            } else {
                // 创建新用户
                $user = User::create([
                    'username' => 'dd_' . substr($dingdingUserInfo['userid'], -8),
                    'nickname' => $dingdingUserInfo['name'],
                    'mobile' => $dingdingUserInfo['mobile'] ?? '',
                    'email' => $dingdingUserInfo['email'] ?? '',
                    'avatar' => $dingdingUserInfo['avatar'] ?? '',
                    'dingding_userid' => $dingdingUserInfo['userid'],
                    'dingding_corpid' => $dingdingUserInfo['corp_id'] ?? '',
                    'status' => 'normal',
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
            }
        }
        
        return $user;
    }

    /**
     * 验证钉钉token
     */
    public function checkDingdingToken()
    {
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }
        
        // 处理Bearer token格式
        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }
        
        // 验证session中的token
        $sessionToken = session('dingding_token');
        if ($token !== $sessionToken) {
            $this->error('token无效');
        }
        
        $this->success('token有效');
    }

    /**
     * 测试接口
     */
    public function test()
    {
        try {
            // 检查数据库连接
            $result = [];
            
            // 记录错误信息
            error_log('test - starting database check');
            
            // 检查表是否存在
            $tables = ['scanwork_allocation', 'scanwork_report', 'scanwork_order', 'scanwork_model', 'scanwork_product', 'scanwork_process'];
            foreach ($tables as $table) {
                try {
                    $exists = Db::query("SHOW TABLES LIKE '{$table}'");
                    $result[$table] = !empty($exists);
                    error_log("test - table {$table}: " . ($result[$table] ? 'exists' : 'not exists'));
                } catch (Exception $e) {
                    error_log("test - error checking table {$table}: " . $e->getMessage());
                    $result[$table] = false;
                }
            }
            
            // 检查各表的数据量
            if ($result['scanwork_allocation']) {
                try {
                    $result['allocation_count'] = Db::name('scanwork_allocation')->count();
                    error_log("test - allocation_count: " . $result['allocation_count']);
                } catch (Exception $e) {
                    error_log("test - error counting allocations: " . $e->getMessage());
                    $result['allocation_count'] = 'error';
                }
            }
            if ($result['scanwork_report']) {
                try {
                    $result['report_count'] = Db::name('scanwork_report')->count();
                    error_log("test - report_count: " . $result['report_count']);
                } catch (Exception $e) {
                    error_log("test - error counting reports: " . $e->getMessage());
                    $result['report_count'] = 'error';
                }
            }
            if ($result['scanwork_order']) {
                try {
                    $result['order_count'] = Db::name('scanwork_order')->count();
                    error_log("test - order_count: " . $result['order_count']);
                } catch (Exception $e) {
                    error_log("test - error counting orders: " . $e->getMessage());
                    $result['order_count'] = 'error';
                }
            }
            
            // 检查当前登录用户
            try {
                if ($this->auth->isLogin()) {
                    $user = $this->auth->getUserinfo();
                    $result['current_user'] = $user;
                    error_log("test - current_user: " . json_encode($user));
                    
                    if ($result['scanwork_allocation']) {
                        try {
                            $result['user_allocations'] = Db::name('scanwork_allocation')->where('user_id', $user['id'])->count();
                            error_log("test - user_allocations: " . $result['user_allocations']);
                        } catch (Exception $e) {
                            error_log("test - error counting user allocations: " . $e->getMessage());
                            $result['user_allocations'] = 'error';
                        }
                    }
                } else {
                    $result['current_user'] = 'not_login';
                    error_log("test - user not logged in");
                }
            } catch (Exception $e) {
                error_log("test - error checking user: " . $e->getMessage());
                $result['current_user'] = 'error: ' . $e->getMessage();
            }
            
            error_log("test - final result: " . json_encode($result));
            $this->success('数据库检查完成', $result);
        } catch (Exception $e) {
            error_log("test - main error: " . $e->getMessage());
            $this->error('数据库检查失败：' . $e->getMessage());
        }
    }

    /**
     * 数据库连接测试
     */
    public function dbTest()
    {
        try {
            // 测试基本数据库连接
            $result = [];
            
            // 获取数据库配置
            $config = config('database');
            $result['database_config'] = [
                'hostname' => $config['hostname'],
                'database' => $config['database'],
                'username' => $config['username'],
                'hostport' => $config['hostport']
            ];
            
            // 测试简单查询
            $testQuery = Db::query("SELECT 1 as test");
            $result['simple_query'] = $testQuery;
            
            // 获取所有表
            $tables = Db::query("SHOW TABLES");
            $result['all_tables'] = $tables;
            
            // 检查scanwork相关表
            $scanworkTables = Db::query("SHOW TABLES LIKE 'scanwork_%'");
            $result['scanwork_tables'] = $scanworkTables;
            
            $this->success('数据库连接测试完成', $result);
        } catch (Exception $e) {
            $this->error('数据库连接测试失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        // 认证检查已经在_initialize中的checkDingdingAuth处理
        $userId = $this->currentUserId;
        
        if (!$userId) {
            $this->error('用户信息无效', null, 401);
        }
        
        $user = User::find($userId);
        if (!$user) {
            $this->error('用户不存在', null, 401);
        }
        
        $this->success('获取成功', $user);
    }

    /**
     * 修改用户信息
     */
    public function updateUserInfo()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $password = $this->request->post('password');
        
        $updateData = [];
        
        if ($username) {
            // 检查用户名是否已经修改过（通过检查是否以dd_开头）
            $currentUser = Db::name('user')->where('id', $user['id'])->find();
            if ($currentUser && !str_starts_with($currentUser['username'], 'dd_')) {
                $this->error('用户名只能修改一次');
            }
            
            // 检查用户名是否已存在
            $exists = Db::name('user')->where('username', $username)->where('id', '<>', $user['id'])->find();
            if ($exists) {
                $this->error('用户名已存在');
            }
            $updateData['username'] = $username;
        }
        
        if ($nickname) {
            $updateData['nickname'] = $nickname;
        }
        
        if ($email) {
            // 验证邮箱格式
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $this->error('邮箱格式不正确');
            }
            // 检查邮箱是否已存在
            $exists = Db::name('user')->where('email', $email)->where('id', '<>', $user['id'])->find();
            if ($exists) {
                $this->error('邮箱已被使用');
            }
            $updateData['email'] = $email;
        }
        
        if ($mobile) {
            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
                $this->error('手机号格式不正确');
            }
            // 检查手机号是否已存在
            $exists = Db::name('user')->where('mobile', $mobile)->where('id', '<>', $user['id'])->find();
            if ($exists) {
                $this->error('手机号已被使用');
            }
            $updateData['mobile'] = $mobile;
        }
        
        if ($password) {
            // 验证密码长度
            if (strlen($password) < 6) {
                $this->error('密码长度不能少于6位');
            }
            // 生成新的salt
            $salt = \fast\Random::alnum();
            $updateData['password'] = md5(md5($password) . $salt);
            $updateData['salt'] = $salt;
        }
        
        if (empty($updateData)) {
            $this->error('没有要更新的数据');
        }
        
        $result = Db::name('user')->where('id', $user['id'])->update($updateData);
        
        if ($result) {
            $this->success('更新成功');
        } else {
            $this->error('更新失败');
        }
    }

    /**
     * 获取个人中心数据
     */
    public function profile()
    {
        // 认证检查已经在_initialize中的checkDingdingAuth处理
        // 从当前用户ID获取
        $userId = $this->currentUserId;
        
        if (!$userId) {
            $this->error('用户信息无效', null, 401);
        }
        
        // 获取完整的用户信息
        $fullUser = Db::name('user')->where('id', $userId)->find();
        
        // 格式化时间
        if ($fullUser) {
            $fullUser['jointime'] = $fullUser['jointime'] ? date('Y-m-d H:i:s', $fullUser['jointime']) : '';
            $fullUser['logintime'] = $fullUser['logintime'] ? date('Y-m-d H:i:s', $fullUser['logintime']) : '';
            $fullUser['createtime'] = $fullUser['createtime'] ? date('Y-m-d H:i:s', $fullUser['createtime']) : '';
        }
        
        // 获取统计数据
        $today = date('Y-m-d');
        $startTime = strtotime($today . ' 00:00:00');
        $endTime = strtotime($today . ' 23:59:59');
        
        // 今日任务数
        $todayTaskCount = Db::name('scanwork_allocation')
            ->where('user_id', $userId)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->count();
        
        // 今日报工数
        $todayReportCount = Db::name('scanwork_report')
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->sum('quantity');
        
        // 今日工资
        $todayWage = Db::name('scanwork_report')
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->sum('wage');
        
        // 总统计数据
        $totalTasks = Db::name('scanwork_allocation')->where('user_id', $userId)->count();
        $totalReports = Db::name('scanwork_report')->where('user_id', $userId)->count();
        $totalWage = Db::name('scanwork_report')->where('user_id', $userId)->where('status', 1)->sum('wage');
        
        $this->success('获取成功', [
            'user' => $fullUser ?: ['id' => $userId],
            'todayTaskCount' => $todayTaskCount,
            'todayReportCount' => $todayReportCount,
            'todayWage' => $todayWage ?: 0,
            'totalTasks' => $totalTasks,
            'totalReports' => $totalReports,
            'totalWage' => $totalWage ?: 0
        ]);
    }

    /**
     * 获取任务列表
     */
    public function getTasks()
    {
        // 认证检查已经在_initialize中的checkDingdingAuth处理
        // 从当前用户ID获取
        $workerId = $this->currentUserId;
        
        if (!$workerId) {
            $this->error('用户信息无效', null, 401);
        }
        
        $tasks = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.user_id', $workerId)
            ->where('a.status', 0)
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('a.createtime desc')
            ->select();
        
        $this->success('获取成功', $tasks);
    }

    /**
     * 获取报工页面数据
     */
    public function getReportData()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $allocationId = $this->request->param('allocation_id') ?: $this->request->param('id');
        
        if (!$allocationId) {
            $this->error('未指定任务ID');
        }
        
        $allocation = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.id', $allocationId)
            ->where('a.user_id', $user['id'])
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->find();
        
        if (!$allocation) {
            $this->error('任务不存在或不属于当前用户');
        }
        
        // 获取可报工的产品编号
        $productItems = Db::name('scanwork_product_item')
            ->where('allocation_id', $allocationId)
            ->where('status', 0) // 未报工状态
            ->order('item_no')
            ->select();
        
        // 计算已报数量和待报数量
        $reportedQuantity = Db::name('scanwork_report')
            ->where('allocation_id', $allocationId)
            ->where('status', 1)
            ->sum('quantity');
        
        $allocation['reported_quantity'] = intval($reportedQuantity);
        $allocation['remaining_quantity'] = max(0, $allocation['quantity'] - $allocation['reported_quantity']);
        $allocation['product_items'] = $productItems;
        
        $this->success('获取成功', $allocation);
    }

    /**
     * 扫码报工
     */
    public function scanReport()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $workerId = $this->auth->id;
        $qrCode = $this->request->post('qr_code');
        
        if (!$qrCode) {
            $this->error('二维码数据不能为空');
        }
        
        // 解析二维码数据（格式：allocation_id）
        $allocationId = $qrCode;
        
        // 验证分配记录
        $allocation = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.id', $allocationId)
            ->where('a.user_id', $workerId)
            ->where('a.status', 0)
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->find();
        
        if (!$allocation) {
            $this->error('无效的二维码或任务已完成');
        }
        
        // 计算剩余数量
        $reportedQuantity = Db::name('scanwork_report')
            ->where('allocation_id', $allocationId)
            ->where('status', 1)
            ->sum('quantity');
        
        $remainingQuantity = max(0, $allocation['quantity'] - $reportedQuantity);
        
        if ($remainingQuantity <= 0) {
            $this->error('该任务已无待报数量');
        }
        
        $allocation['remaining_quantity'] = $remainingQuantity;
        $this->success('扫码成功', $allocation);
    }

    /**
     * 提交报工
     */
    public function submitReport()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $workerId = $user['id'];
        
        // 获取参数
        $allocationId = intval($this->request->post('allocation_id', 0));
        $itemNos = $this->request->post('item_nos/a', []); // 产品编号数组
        $workType = $this->request->post('work_type', 'piece');
        $workHours = floatval($this->request->post('work_hours', 0));
        $remark = $this->request->post('remark', '');
        $imageUrls = $this->request->post('image_urls/a', []); // 图片URL数组
        
        // 验证参数
        if (empty($allocationId)) {
            $this->error('分工ID不能为空');
        }
        
        if ($workType == 'piece' && empty($itemNos)) {
            $this->error('产品编号不能为空');
        }
        
        if ($workType == 'time' && empty($workHours)) {
            $this->error('工时不能为空');
        }
        
        try {
            // 验证分工是否存在且属于当前用户
            $allocation = Db::name('scanwork_allocation')->where('id', $allocationId)->find();
            if (!$allocation) {
                $this->error('分工不存在');
            }
            
            if ($allocation['user_id'] != $workerId) {
                $this->error('无权操作此分工');
            }
            
            // 如果是计件工作，验证产品编号
            if ($workType == 'piece') {
                foreach ($itemNos as $itemNo) {
                    $item = Db::name('scanwork_product_item')
                        ->where('allocation_id', $allocationId)
                        ->where('item_no', $itemNo)
                        ->find();
                    
                    if (!$item) {
                        $this->error('产品编号不存在: ' . $itemNo);
                    }
                    
                    if ($item['status'] != 0) {
                        $this->error('该产品编号已报工: ' . $itemNo);
                    }
                }
            }
            
            Db::startTrans();
            
            try {
                // 创建报工记录
                $reportData = [
                    'allocation_id' => $allocationId,
                    'user_id' => $workerId,
                    'type' => $workType,
                    'quantity' => $workType == 'piece' ? count($itemNos) : $workHours,
                    'item_nos' => $workType == 'piece' ? json_encode($itemNos) : '',
                    'work_hours' => $workType == 'time' ? $workHours : null,
                    'remark' => $remark,
                    'status' => 0,
                    'wage' => 0,
                    'report_time' => time(),
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                
                $reportId = Db::name('scanwork_report')->insertGetId($reportData);
                
                // 如果是计件工作，更新产品编号状态
                if ($workType == 'piece') {
                    foreach ($itemNos as $itemNo) {
                        Db::name('scanwork_product_item')
                            ->where('allocation_id', $allocationId)
                            ->where('item_no', $itemNo)
                            ->update([
                                'status' => 1,
                                'report_id' => $reportId,
                                'updatetime' => time()
                            ]);
                    }
                    
                    // 保存图片
                    if (!empty($imageUrls) && is_array($imageUrls)) {
                        foreach ($imageUrls as $imageUrl) {
                            try {
                                // 获取第一个产品编号的item_id
                                $firstItem = Db::name('scanwork_product_item')
                                    ->where('allocation_id', $allocationId)
                                    ->where('item_no', $itemNos[0])
                                    ->find();
                                
                                if ($firstItem) {
                                    Db::name('scanwork_item_report_image')->insert([
                                        'item_id' => $firstItem['id'],
                                        'report_id' => $reportId,
                                        'image_url' => $imageUrl,
                                        'upload_user_id' => $workerId,
                                        'createtime' => time()
                                    ]);
                                }
                            } catch (\Exception $e) {
                                // 不抛出异常，继续执行
                            }
                        }
                    }
                }
                
                // 更新分工的已报数量
                Db::name('scanwork_allocation')
                    ->where('id', $allocationId)
                    ->setInc('reported_quantity', $workType == 'piece' ? count($itemNos) : $workHours);
                
                Db::commit();
                
                $response = [
                    'report_id' => $reportId,
                    'item_no' => $itemNos[0] // 返回第一个产品编号
                ];
                
                $this->success('报工成功', $response);
                
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('报工失败：' . $e->getMessage());
            }
            
        } catch (\Exception $e) {
            $this->error('报工失败：' . $e->getMessage());
        }
    }

    /**
     * 上传报工图片
     */
    public function uploadImage()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $itemNo = $this->request->post('item_no', ''); // 产品编号
        $reportId = $this->request->post('report_id', 0); // 报工ID
        
        if (!empty($_FILES['file'])) {
            $file = $_FILES['file'];
            
            if ($file['error'] == 0) {
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $allowExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'jfif'];
                if (!in_array(strtolower($ext), $allowExt)) {
                    $this->error('不支持的文件格式');
                }
                
                if ($file['size'] > 10 * 1024 * 1024) {
                    $this->error('文件大小不能超过10MB');
                }
                
                $filename = uniqid() . '_' . ($itemNo ?: 'report') . '.' . $ext;
                $dateDir = date('Y-m-d');
                $uploadDir = 'uploads/baogong/' . $dateDir . '/';
                
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $filepath = $uploadDir . $filename;
                
                if (move_uploaded_file($file['tmp_name'], $filepath)) {
                    $imageUrl = '/uploads/baogong/' . $dateDir . '/' . $filename;
                    
                    // 如果有报工ID，直接保存图片记录
                    if ($reportId > 0 && !empty($itemNo)) {
                        try {
                            $item = Db::name('scanwork_product_item')
                                ->where('item_no', $itemNo)
                                ->find();
                            
                            if ($item) {
                                Db::name('scanwork_item_report_image')->insert([
                                    'item_id' => $item['id'],
                                    'report_id' => $reportId,
                                    'image_url' => $imageUrl,
                                    'upload_user_id' => $user['id'],
                                    'createtime' => time()
                                ]);
                            }
                        } catch (\Exception $e) {
                            // 记录错误但不影响上传
                        }
                    }
                    
                    $this->success('上传成功', [
                        'url' => $imageUrl
                    ]);
                } else {
                    $this->error('文件上传失败');
                }
            } else {
                $this->error('文件上传错误');
            }
        } else {
            $this->error('没有选择文件');
        }
    }

    /**
     * 获取报工记录
     */
    public function getRecords()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        
        $records = Db::name('scanwork_report')
            ->where('user_id', $user['id'])
            ->order('createtime desc')
            ->select();
        
        // 为每条记录补充详细信息
        foreach ($records as &$record) {
            $allocation = Db::name('scanwork_allocation')->where('id', $record['allocation_id'])->find();
            
            if ($allocation) {
                $order = Db::name('scanwork_order')->where('id', $allocation['order_id'])->find();
                $record['order_no'] = $order ? $order['order_no'] : '';
                
                $model = Db::name('scanwork_model')->where('id', $allocation['model_id'])->find();
                $record['model_name'] = $model ? $model['name'] : '';
                
                if ($model) {
                    $product = Db::name('scanwork_product')->where('id', $model['product_id'])->find();
                    $record['product_name'] = $product ? $product['name'] : '';
                } else {
                    $record['product_name'] = '';
                }
                
                $process = Db::name('scanwork_process')->where('id', $allocation['process_id'])->find();
                $record['process_name'] = $process ? $process['name'] : '';
            } else {
                $record['order_no'] = '';
                $record['model_name'] = '';
                $record['product_name'] = '';
                $record['process_name'] = '';
            }
            
            // 格式化时间
            $record['createtime_text'] = date('Y-m-d H:i:s', $record['createtime']);
            $record['status_text'] = $record['status'] == 1 ? '已确认' : '待确认';
        }
        
        $this->success('获取成功', [
            'list' => $records,
            'total' => count($records),
            'page' => 1,
            'limit' => count($records)
        ]);
    }

    /**
     * 获取工资统计
     */
    public function getWageStats()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $month = $this->request->param('month', date('Y-m'));
        
        $startTime = strtotime($month . '-01 00:00:00');
        $endTime = strtotime($month . '-' . date('t', $startTime) . ' 23:59:59');
        
        $wages = Db::name('scanwork_report')
            ->alias('r')
            ->join('scanwork_allocation a', 'r.allocation_id = a.id')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('r.user_id', $user['id'])
            ->where('r.status', 1)
            ->where('r.createtime', 'between', [$startTime, $endTime])
            ->field('r.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('r.createtime desc')
            ->select();
        
        $totalWage = array_sum(array_column($wages, 'wage'));
        
        $this->success('获取成功', [
            'reports' => $wages,
            'total_quantity' => array_sum(array_column($wages, 'quantity')),
            'total_wage' => $totalWage,
            'start_date' => date('Y-m-01', $startTime),
            'end_date' => date('Y-m-d', $endTime)
        ]);
    }

    /**
     * 调试：检查订单信息
     */
    public function debugOrder()
    {
        $order_id = $this->request->get('order_id');
        if (!$order_id) {
            $this->error('参数错误');
        }

        // 检查订单
        $order = \app\admin\model\scanwork\Order::find($order_id);
        if (!$order) {
            $this->error('订单不存在');
        }

        // 检查订单型号
        $orderModels = \app\admin\model\scanwork\OrderModel::with(['model.product'])
            ->where('order_id', $order_id)
            ->select();

        // 检查工序
        $processes = \app\admin\model\scanwork\Process::where('status', 1)->select();

        // 检查工价设置
        $processPrices = \app\admin\model\scanwork\ProcessPrice::select();

        $debug = [
            'order' => $order,
            'order_models_count' => count($orderModels),
            'order_models' => $orderModels,
            'processes_count' => count($processes),
            'processes' => $processes,
            'process_prices_count' => count($processPrices),
            'process_prices' => $processPrices
        ];

        $this->success('调试信息', $debug);
    }

    /**
     * 获取统计数据
     */
    public function getStats()
    {
        // 认证检查已经在_initialize中的checkDingdingAuth处理
        // 从当前用户ID获取
        $workerId = $this->currentUserId;
        
        file_put_contents('/tmp/dingding_stats.log', "getStats调试 - currentUserId: " . ($workerId ?? 'null') . "\n", FILE_APPEND);
        file_put_contents('/tmp/dingding_stats.log', "getStats调试 - currentUser: " . ($this->currentUser ? 'exists' : 'null') . "\n", FILE_APPEND);
        
        if (!$workerId) {
            file_put_contents('/tmp/dingding_stats.log', "getStats错误 - 用户信息无效\n", FILE_APPEND);
            $this->error('用户信息无效', null, 401);
        }
        
        file_put_contents('/tmp/dingding_stats.log', "getStats调试 - 开始查询用户ID: {$workerId} 的统计数据\n", FILE_APPEND);
        
        // 获取今日数据
        $today = date('Y-m-d');
        $startTime = strtotime($today . ' 00:00:00');
        $endTime = strtotime($today . ' 23:59:59');
        
        // 今日任务数
        $todayTaskCount = Db::name('scanwork_allocation')
            ->where('user_id', $workerId)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->count();
        
        // 今日报工数
        $todayReportCount = Db::name('scanwork_report')
            ->where('user_id', $workerId)
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->sum('quantity');
        
        // 今日工资
        $todayWage = Db::name('scanwork_report')
            ->where('user_id', $workerId)
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->sum('wage');
        
        file_put_contents('/tmp/dingding_stats.log', "getStats调试 - 今日数据: 任务数={$todayTaskCount}, 报工数={$todayReportCount}, 工资={$todayWage}\n", FILE_APPEND);
        
        // 获取最近7天的数据
        $dates = [];
        $quantities = [];
        $wages = [];
        
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $dates[] = $date;
            
            $quantity = Db::name('scanwork_report')
                ->where('user_id', $workerId)
                ->where('status', 1)
                ->where('createtime', 'between', [strtotime($date), strtotime($date . ' 23:59:59')])
                ->sum('quantity');
            
            $wage = Db::name('scanwork_report')
                ->where('user_id', $workerId)
                ->where('status', 1)
                ->where('createtime', 'between', [strtotime($date), strtotime($date . ' 23:59:59')])
                ->sum('wage');
            
            $quantities[] = intval($quantity);
            $wages[] = floatval($wage);
        }
        
        $result = [
            'taskCount' => $todayTaskCount,
            'reportCount' => intval($todayReportCount),
            'wage' => floatval($todayWage),
            'dates' => $dates,
            'quantities' => $quantities,
            'wages' => $wages
        ];
        
        file_put_contents('/tmp/dingding_stats.log', "getStats调试 - 返回结果: " . json_encode($result) . "\n", FILE_APPEND);
        
        $this->success('获取成功', $result);
    }

    /**
     * 获取消息列表
     */
    public function getMessages()
    {
        // 认证检查已经在_initialize中的checkDingdingAuth处理
        $userId = $this->currentUserId;
        
        if (!$userId) {
            $this->error('用户信息无效', null, 401);
        }
        
        // 获取用户的消息列表（这里可以根据实际需求实现）
        $messages = [
            [
                'id' => 1,
                'title' => '系统通知',
                'content' => '欢迎使用工厂报工系统',
                'type' => 'system',
                'is_read' => 0,
                'create_time' => date('Y-m-d H:i:s')
            ]
        ];
        
        $this->success('获取成功', $messages);
    }

    /**
     * 获取订单列表
     */
    public function getOrders()
    {
        // 认证检查已经在_initialize中的checkDingdingAuth处理
        $userId = $this->currentUserId;
        
        if (!$userId) {
            $this->error('用户信息无效', null, 401);
        }
        
        // 获取订单列表 - 修复状态查询条件
        $orders = Db::name('scanwork_order')
            ->where('status', 'in', [0, 1]) // 0: pending, 1: processing
            ->order('createtime desc')
            ->select();
        
        $this->success('获取成功', $orders ?: []);
    }

    /**
     * 获取工序列表
     */
    public function getProcesses()
    {
        // 认证检查已经在_initialize中的checkDingdingAuth处理
        $userId = $this->currentUserId;
        
        if (!$userId) {
            $this->error('用户信息无效', null, 401);
        }
        
        // 获取工序列表
        $processes = Db::name('scanwork_process')
            ->where('status', 1)
            ->order('createtime desc')
            ->select();
        
        $this->success('获取成功', $processes ?: []);
    }

    /**
     * 获取计时任务列表
     */
    public function getTimeTasks()
    {
        // 认证检查已经在_initialize中的checkDingdingAuth处理
        $userId = $this->currentUserId;
        
        if (!$userId) {
            $this->error('用户信息无效', null, 401);
        }
        
        // 获取计时任务列表
        $tasks = Db::name('scanwork_tallocationtime')
            ->alias('t')
            ->join('scanwork_order o', 't.order_id = o.id')
            ->join('scanwork_process p', 't.process_id = p.id')
            ->join('scanwork_model m', 't.model_id = m.id')
            ->where('t.user_id', $userId)
            ->where('t.status', 0) // 0: 进行中
            ->field('t.*, o.order_no, o.title as order_title, p.name as process_name, m.name as model_name')
            ->order('t.work_date desc, t.createtime desc')
            ->select();
        
        // 格式化数据
        foreach ($tasks as &$task) {
            $task['title'] = $task['order_title'] ?: '计时任务';
            $task['description'] = "订单：{$task['order_no']} | 工序：{$task['process_name']} | 型号：{$task['model_name']}";
            $task['estimated_hours'] = $task['total_hours'] ?: 0;
            $task['actual_hours'] = $task['reported_total_hours'] ?: 0;
            $task['hourly_rate'] = $task['price'] ?: 0;
            $task['status'] = $task['status'];
            
            // 格式化时间
            if ($task['work_date']) {
                $task['work_date_text'] = date('Y-m-d', strtotime($task['work_date']));
            }
            if ($task['createtime']) {
                $task['createtime_text'] = date('Y-m-d H:i:s', $task['createtime']);
            }
        }
        
        $this->success('获取成功', $tasks ?: []);
    }

    /**
     * 主动报工
     */
    public function activeReport()
    {
        // 认证检查已经在_initialize中的checkDingdingAuth处理
        $userId = $this->currentUserId;
        
        if (!$userId) {
            $this->error('用户信息无效', null, 401);
        }
        
        // 获取参数
        $orderId = intval($this->request->post('order_id', 0));
        $processId = intval($this->request->post('process_id', 0));
        $workType = $this->request->post('work_type', 'piece');
        $quantity = intval($this->request->post('quantity', 0));
        $workHours = floatval($this->request->post('work_hours', 0));
        $remark = $this->request->post('remark', '');
        $imageUrls = $this->request->post('image_urls/a', []);
        
        // 验证参数
        if (empty($orderId)) {
            $this->error('订单ID不能为空');
        }
        
        if (empty($processId)) {
            $this->error('工序ID不能为空');
        }
        
        if ($workType == 'piece' && empty($quantity)) {
            $this->error('数量不能为空');
        }
        
        if ($workType == 'time' && empty($workHours)) {
            $this->error('工时不能为空');
        }
        
        try {
            // 验证订单是否存在
            $order = Db::name('scanwork_order')->where('id', $orderId)->find();
            if (!$order) {
                $this->error('订单不存在');
            }
            
            // 验证工序是否存在
            $process = Db::name('scanwork_process')->where('id', $processId)->find();
            if (!$process) {
                $this->error('工序不存在');
            }
            
            Db::startTrans();
            
            try {
                // 创建主动报工记录
                $reportData = [
                    'user_id' => $userId,
                    'order_id' => $orderId,
                    'process_id' => $processId,
                    'type' => $workType,
                    'quantity' => $workType == 'piece' ? $quantity : $workHours,
                    'work_hours' => $workType == 'time' ? $workHours : null,
                    'remark' => $remark,
                    'status' => 0, // 待审核
                    'wage' => 0, // 工资待计算
                    'report_time' => time(),
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                
                $reportId = Db::name('scanwork_report')->insertGetId($reportData);
                
                // 保存图片
                if (!empty($imageUrls) && is_array($imageUrls)) {
                    foreach ($imageUrls as $imageUrl) {
                        Db::name('scanwork_report_image')->insert([
                            'report_id' => $reportId,
                            'image_url' => $imageUrl,
                            'upload_user_id' => $userId,
                            'createtime' => time()
                        ]);
                    }
                }
                
                Db::commit();
                
                $this->success('主动报工提交成功', [
                    'report_id' => $reportId
                ]);
                
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('主动报工失败：' . $e->getMessage());
            }
            
        } catch (\Exception $e) {
            $this->error('主动报工失败：' . $e->getMessage());
        }
    }

    /**
     * 绑定现有用户
     */
    public function bindExistingUser()
    {
        $tempToken = $this->request->post('temp_token');
        $userId = $this->request->post('user_id');
        $password = $this->request->post('password');
        
        if (!$tempToken || !$userId || !$password) {
            $this->error('参数不完整');
        }
        
        // 验证临时token
        $tempData = Db::name('dingding_temp_login')
            ->where('temp_token', $tempToken)
            ->where('expiretime', '>', time())
            ->find();
            
        if (!$tempData) {
            $this->error('临时token无效或已过期');
        }
        
        // 获取钉钉用户信息
        $dingdingUserInfo = json_decode($tempData['dingding_user_info'], true);
        $corpId = $tempData['corp_id'];
        
        if (!$dingdingUserInfo || !$corpId) {
            $this->error('钉钉用户信息无效');
        }
        
        // 查找现有用户
        $user = User::find($userId);
        if (!$user) {
            $this->error('用户不存在');
        }
        
        // 验证密码
        $salt = $user->salt;
        $encryptedPassword = md5(md5($password) . $salt);
        if ($encryptedPassword !== $user->password) {
            $this->error('密码错误');
        }
        
        // 检查用户是否已绑定其他钉钉账号
        if (!empty($user->dingding_userid) && $user->dingding_userid !== $dingdingUserInfo['userid']) {
            $this->error('该用户已绑定其他钉钉账号');
        }
        
        // 绑定钉钉账号
        $user->dingding_userid = $dingdingUserInfo['userid'];
        $user->dingding_corpid = $corpId;
        $user->save();
        
        // 生成正式token
        $token = md5($user->id . time() . rand(1000, 9999));
        
        // 保存token到数据库
        $user->dingding_token = $token;
        $user->dingding_token_expire = time() + 7200; // 2小时过期
        $user->save();
        
        // 保存到session
        $sessionData = [
            'user_id' => $user->id,
            'dingding_user_id' => $dingdingUserInfo['userid'],
            'corp_id' => $corpId,
            'name' => $dingdingUserInfo['name'],
            'department_ids' => $dingdingUserInfo['department_ids'] ?? [],
            'login_time' => time()
        ];
        
        session('dingding_user_info', $sessionData);
        session('dingding_token', $token);
        
        // 清除临时信息
        Db::name('dingding_temp_login')->where('temp_token', $tempToken)->delete();
        
        $this->success('绑定成功', [
            'token' => $token,
            'user' => $user,
            'dingding_info' => $dingdingUserInfo
        ]);
    }

    /**
     * 创建新用户
     */
    public function createNewUser()
    {
        $tempToken = $this->request->post('temp_token');
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $nickname = $this->request->post('nickname');
        
        // 记录调试信息
        file_put_contents('/tmp/dingding_create.log', "创建用户调试 - tempToken: " . ($tempToken ?: 'null') . "\n", FILE_APPEND);
        file_put_contents('/tmp/dingding_create.log', "创建用户调试 - username: " . ($username ?: 'null') . "\n", FILE_APPEND);
        file_put_contents('/tmp/dingding_create.log', "创建用户调试 - password: " . ($password ? 'exists' : 'null') . "\n", FILE_APPEND);
        file_put_contents('/tmp/dingding_create.log', "创建用户调试 - nickname: " . ($nickname ?: 'null') . "\n", FILE_APPEND);
        
        if (!$tempToken || !$username || !$password) {
            file_put_contents('/tmp/dingding_create.log', "创建用户错误 - 参数不完整\n", FILE_APPEND);
            $this->error('参数不完整');
        }
        
        // 验证临时token
        $tempData = Db::name('dingding_temp_login')
            ->where('temp_token', $tempToken)
            ->where('expiretime', '>', time())
            ->find();
            
        if (!$tempData) {
            $this->error('临时token无效或已过期');
        }
        
        // 获取钉钉用户信息
        $dingdingUserInfo = json_decode($tempData['dingding_user_info'], true);
        $corpId = $tempData['corp_id'];
        
        if (!$dingdingUserInfo || !$corpId) {
            $this->error('钉钉用户信息无效');
        }
        
        // 验证用户名
        if (strlen($username) < 3) {
            $this->error('用户名长度不能少于3位');
        }
        
        // 检查用户名是否已存在
        $exists = User::where('username', $username)->find();
        if ($exists) {
            $this->error('用户名已存在');
        }
        
        // 验证密码
        if (strlen($password) < 6) {
            $this->error('密码长度不能少于6位');
        }
        
        // 生成salt和加密密码
        $salt = \fast\Random::alnum();
        $encryptedPassword = md5(md5($password) . $salt);
        
        // 创建新用户
        $user = User::create([
            'username' => $username,
            'nickname' => $nickname ?: $dingdingUserInfo['name'],
            'password' => $encryptedPassword,
            'salt' => $salt,
            'mobile' => $dingdingUserInfo['mobile'] ?? '',
            'email' => $dingdingUserInfo['email'] ?? '',
            'avatar' => $dingdingUserInfo['avatar'] ?? '',
            'dingding_userid' => $dingdingUserInfo['userid'],
            'dingding_corpid' => $corpId,
            'status' => 'normal',
            'createtime' => time(),
            'updatetime' => time()
        ]);
        
        // 生成正式token
        $token = md5($user->id . time() . rand(1000, 9999));
        
        // 保存token到数据库
        $user->dingding_token = $token;
        $user->dingding_token_expire = time() + 7200; // 2小时过期
        $user->save();
        
        // 保存到session
        $sessionData = [
            'user_id' => $user->id,
            'dingding_user_id' => $dingdingUserInfo['userid'],
            'corp_id' => $corpId,
            'name' => $dingdingUserInfo['name'],
            'department_ids' => $dingdingUserInfo['department_ids'] ?? [],
            'login_time' => time()
        ];
        
        session('dingding_user_info', $sessionData);
        session('dingding_token', $token);
        
        // 清除临时信息
        Db::name('dingding_temp_login')->where('temp_token', $tempToken)->delete();
        
        $this->success('创建成功', [
            'token' => $token,
            'user' => $user,
            'dingding_info' => $dingdingUserInfo
        ]);
    }

    /**
     * 管理员登录
     */
    public function adminLogin()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        
        if (!$username || !$password) {
            $this->error('用户名和密码不能为空');
        }
        
        // 查找用户
        $user = User::where('username', $username)->find();
        if (!$user) {
            $this->error('用户不存在');
        }
        
        // 验证密码
        $salt = $user->salt;
        $encryptedPassword = md5(md5($password) . $salt);
        if ($encryptedPassword !== $user->password) {
            $this->error('密码错误');
        }
        
        // 检查是否为管理员
        if ($user->status !== 'normal') {
            $this->error('用户状态异常');
        }
        
        // 生成管理员token
        $adminToken = md5('admin_' . $user->id . time() . rand(1000, 9999));
        
        // 保存管理员token到数据库
        $user->dingding_token = $adminToken;
        $user->dingding_token_expire = time() + 7200; // 2小时过期
        $user->save();
        
        // 保存到session
        session('dingding_current_user_id', $user->id);
        session('dingding_token', $adminToken);
        session('admin_info', [
            'id' => $user->id,
            'username' => $user->username,
            'nickname' => $user->nickname,
            'mobile' => $user->mobile,
            'email' => $user->email,
            'avatar' => $user->avatar
        ]);
        session('admin_token', $adminToken);
        
        $this->success('管理员登录成功', [
            'token' => $adminToken,
            'admin_info' => [
                'id' => $user->id,
                'username' => $user->username,
                'nickname' => $user->nickname,
                'mobile' => $user->mobile,
                'email' => $user->email,
                'avatar' => $user->avatar
            ]
        ]);
    }

    /**
     * 获取所有用户列表（管理员用）
     */
    public function getUsers()
    {
        $users = User::where('status', 'normal')
                    ->field('id, username, nickname, mobile, email, createtime')
                    ->order('createtime desc')
                    ->select();
        
        $this->success('获取成功', $users ?: []);
    }

    /**
     * 获取产品列表
     */
    public function getProducts()
    {
        $products = Db::name('scanwork_product')
                     ->where('status', 1)
                     ->field('id, name, code, description')
                     ->order('createtime desc')
                     ->select();
        
        $this->success('获取成功', $products ?: []);
    }

    /**
     * 获取型号列表
     */
    public function getModels()
    {
        $models = Db::name('scanwork_model')
                   ->where('status', 1)
                   ->field('id, name, code, product_id')
                   ->order('createtime desc')
                   ->select();
        
        $this->success('获取成功', $models ?: []);
    }

    /**
     * 获取所有分工列表（管理员用）
     */
    public function getAllocations()
    {
        $allocations = Db::name('scanwork_allocation')
                        ->alias('a')
                        ->join('scanwork_order o', 'a.order_id = o.id')
                        ->join('fa_user u', 'a.user_id = u.id')
                        ->field('a.*, o.order_no, o.product_name, u.nickname as user_name')
                        ->order('a.createtime desc')
                        ->select();
        
        $this->success('获取成功', $allocations ?: []);
    }

    /**
     * 获取所有报工列表（管理员用）
     */
    public function getReports()
    {
        $reports = Db::name('scanwork_report')
                    ->alias('r')
                    ->join('scanwork_allocation a', 'r.allocation_id = a.id')
                    ->join('scanwork_order o', 'a.order_id = o.id')
                    ->join('fa_user u', 'r.user_id = u.id')
                    ->field('r.*, o.order_no, o.product_name, u.nickname as user_name')
                    ->order('r.createtime desc')
                    ->select();
        
        $this->success('获取成功', $reports ?: []);
    }

    /**
     * 搜索用户
     */
    public function searchUsers()
    {
        $keyword = $this->request->get('keyword');
        
        if (!$keyword) {
            $this->error('请输入搜索关键词');
        }
        
        // 搜索用户（用户名或昵称包含关键词）
        $users = User::where('username', 'like', "%{$keyword}%")
                    ->whereOr('nickname', 'like', "%{$keyword}%")
                    ->field('id, username, nickname, mobile, email')
                    ->limit(10)
                    ->select();
        
        $this->success('搜索成功', $users ?: []);
    }

    /**
     * 获取订单下的产品和型号
     */
    public function getOrderModels()
    {
        // 认证检查已经在_initialize中的checkDingdingAuth处理
        $userId = $this->currentUserId;
        
        if (!$userId) {
            $this->error('用户信息无效', null, 401);
        }
        
        $orderId = intval($this->request->get('order_id', 0));
        
        if (empty($orderId)) {
            $this->error('订单ID不能为空');
        }
        
        // 验证订单是否存在
        $order = Db::name('scanwork_order')->where('id', $orderId)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        
        // 获取订单下的产品型号
        $orderModels = Db::name('scanwork_order_model')
            ->alias('om')
            ->join('scanwork_model m', 'om.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->where('om.order_id', $orderId)
            ->field('om.*, m.name as model_name, m.name as model_code, p.name as product_name, p.name as product_code')
            ->select();
        
        $this->success('获取成功', $orderModels ?: []);
    }
}
